﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Net.IRepository;
using Net.Model.Entities.Enterprises;
using Net.Model.ViewModels.Basic;
using Net.Model.ViewModels.Licenses;
using SqlSugar;

namespace Net.Repository
{
    public class LicenseRepository: BaseRepository<AppLicenses>,ILicenseRepository
    {
        public LicenseRepository(IUnitOfWork unitOfWork):base(unitOfWork)
        {

        }

        public async Task<AppProductLine> AddProductLine(AppProductLine productLine)
        {
            await DbClient.Insertable(productLine).ExecuteCommandAsync();
            return productLine;       
        }

        public async Task<IPageList<LicenseDto>> QueryAppLicensesByEnterpriseName(string enterpriseName)
        {
            int totalCount = 0;
            var data =await DbClient.Queryable<AppEnterpriseLicense, AppLicenses, AppEnterprises>((el, l, e) => new JoinQueryInfos(JoinType.Left, el.LicenseId == l.Id,JoinType.Left ,el.EnterpriseId == e.Id))
                .Select((el, l, e) => new LicenseDto
                {
                    TenantId = e.TenantId,
                    EnterpriseId = e.Id,
                    EnterpriseName = e.EnterpriseName,
                    LicenseId = l.Id,
                    LicenseStartDateUtc = l.LicenseStartDateUtc,
                    LicenseEndDateUtc = l.LicenseEndDateUtc,
                    Cost = l.Cost,
                    Unit =l.Unit,
                    IsActive = l.IsActive,
                    IsDeleted = l.IsDeleted,
                    CreationTime = l.CreationTime,
                    CreatorUserId = l.CreatorUserId,
                    LastModificationTime = l.LastModificationTime,
                    LastModifierUserId = l.LastModifierUserId,
                    DeleterUserId = l.DeleterUserId,
                    DeletionTime = l.DeletionTime,
                }).MergeTable().Where(x=>x.EnterpriseName == enterpriseName && x.IsActive == true && x.IsDeleted == false).OrderBy(x => x.LicenseId).ToPageListAsync(1,50, totalCount);

            var list = new PageList<LicenseDto>(data,1,100,totalCount);
            return list;
        }

        public async Task<List<AppProductLine>> QueryProductLinesByLicenseIds(long[] licenseIds)
        {
            var data = await DbClient.Queryable<AppProductLine>().Where(x => licenseIds.Contains(x.LicenseId)).ToListAsync();
            return data;
        }
    }
}
